package com.cdsf.kennedy.cegs;

import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.cdsf.common.util.BaseJson;
import com.cdsf.kennedy.cegs.service.CEGSService;
import com.cdsf.kennedy.util.ExportExcelUtil;
import com.github.pagehelper.PageInfo;

import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping("/cegs")
public class CEGSController {

    @Autowired
    private CEGSService cegsService;
    @Value("${fileUploadPath}")
    private String fileUploadPath;

    @RequestMapping("/index")
    public String index() {
        return "index";
    }


    @RequestMapping("/list")
    public String list() {
        return "list";
    }

    @RequestMapping("/compareResult")
    public String compareResult() {
        return "compare-result";
    }

    @RequestMapping("/userinfo")
    public String userinfo() {
        return "user-info";
    }

    /**
     * 各病区人员数统计
     */
    @ApiOperation("获取各病区人员数")
    @RequestMapping("/getDoorUserCountList")
    @ResponseBody
    public BaseJson getDoorUserCountList(@RequestBody Map paramMap) {
        BaseJson baseJson = new BaseJson();
        try {
            List<Map<String, Object>> result = cegsService.getDoorUserCountList(paramMap);
            baseJson.setStatus(true);
            baseJson.setData(result);
        } catch (Exception e) {
            e.printStackTrace();
            baseJson.setStatus(false);
            baseJson.setMessage(e.getMessage());
        }
        return baseJson;
    }

    /**
     * 获取病区人员名单
     */
    @ApiOperation("获取病区人员名单")
    @RequestMapping("/getDoorUserList")
    @ResponseBody
    public BaseJson getDoorUserList(@RequestBody Map paramMap) {
        BaseJson baseJson = new BaseJson();
        try {
            PageInfo<Map<String, Object>> result = cegsService.getDoorUserListByPage(paramMap);
            baseJson.setStatus(true);
            baseJson.setData(result);
        } catch (Exception e) {
            e.printStackTrace();
            baseJson.setStatus(false);
            baseJson.setMessage(e.getMessage());
        }
        return baseJson;
    }

    /**
     * 根据病区导出人员名单
     */
    @ApiOperation("根据病区导出人员名单")
    @GetMapping("/exportDoorUserList")
    @ResponseBody
    public void exportDoorUserList(@RequestParam(required = false) String doorCode, @RequestParam(required = false) String deviceNo, @RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate, HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("doorCode", doorCode);
            paramMap.put("deviceNo", deviceNo);
            paramMap.put("startDate", startDate);
            paramMap.put("endDate", endDate);
            List<Map<String, Object>> result = cegsService.getDoorUserList(paramMap);
            String[] fieldName = new String[]{"序号", "姓名", "身份证号", "病区编码", "病区名称", "设备编号", "设备名称"};
            List<Object[]> data = new LinkedList<>();
            result.forEach(record -> {
                data.add(new String[]{"", record.get("name").toString(), record.getOrDefault("cardno", "").toString(), record.get("doorCode").toString(), record.get("doorName").toString(), record.get("deviceNo").toString(), record.get("deviceName").toString()});
            });
            ExportExcelUtil excelUtil = new ExportExcelUtil("病区人员名单", fieldName, data, request, response);
            excelUtil.exportData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 文件上传
     */
    @RequestMapping("/fileUpload")
    @ResponseBody
    public BaseJson fileUpload(String doorCode, @RequestParam("fileName") MultipartFile file) {
        BaseJson baseJson = new BaseJson();
        if (file.isEmpty()) {
            baseJson.setMessage("请选择上传文件");
            baseJson.setStatus(false);
            return baseJson;
        }
        try {
            File dest = new File(fileUploadPath + "/" + doorCode + ".xlsx");
            //判断文件父目录是否存在
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdir();
            }
            file.transferTo(dest);
            // 解析姓名列表
            List<String> nameList = ExportExcelUtil.readExcel(dest);
            baseJson.setData(nameList);
            baseJson.setStatus(true);
        } catch (Exception e) {
            e.printStackTrace();
            baseJson.setMessage(e.getMessage());
            baseJson.setStatus(false);
        }
        return baseJson;
    }

    /**
     * 数据比对
     */
    @RequestMapping("/dataCompare")
    @ResponseBody
    public BaseJson dataCompare(String excelNames, @RequestParam(required = false) String doorCode, @RequestParam(required = false) String deviceNo, @RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate) {
        BaseJson baseJson = new BaseJson();
        try {
            if (!StringUtils.isNotEmpty(excelNames)) {
                baseJson.setMessage("Excel列表不能为空");
                baseJson.setStatus(false);
                return baseJson;
            }
            // 查询待比对列表
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("doorCode", doorCode);
            paramMap.put("deviceNo", deviceNo);
            paramMap.put("startDate", startDate);
            paramMap.put("endDate", endDate);
            List<String> doorUsers = cegsService.getDoorUserNameList(paramMap);
            doorUsers.removeAll(Arrays.asList(excelNames.split(",")));
            baseJson.setData(doorUsers);
            baseJson.setStatus(true);
        } catch (Exception e) {
            e.printStackTrace();
            baseJson.setMessage(e.getMessage());
            baseJson.setStatus(false);
        }
        return baseJson;
    }


    /**
     * 获取病区列表
     */
    @RequestMapping("getDoorInfoList")
    @ResponseBody
    public BaseJson getDoorInfoList() {
        BaseJson baseJson = new BaseJson();
        try {
            List<Map<String, Object>> result = cegsService.getDoorInfoList();
            Map<String, String> res = new HashMap<>();
            result.forEach(record -> {
                res.put(record.get("doorCode").toString(), record.get("doorName").toString());
            });
            baseJson.setStatus(true);
            baseJson.setData(res);
        } catch (Exception e) {
            e.printStackTrace();
            baseJson.setStatus(false);
            baseJson.setMessage(e.getMessage());
        }
        return baseJson;
    }

    /**
     * 获取设备列表
     */
    @RequestMapping("getDeviceInfoList")
    @ResponseBody
    public BaseJson getDeviceInfoList() {
        BaseJson baseJson = new BaseJson();
        try {
            List<Map<String, Object>> result = cegsService.getDeviceInfoList();
            Map<String, String> res = new HashMap<>();
            result.forEach(record -> {
                res.put(record.get("deviceNo").toString(), record.get("deviceName").toString());
            });
            baseJson.setStatus(true);
            baseJson.setData(res);
        } catch (Exception e) {
            e.printStackTrace();
            baseJson.setStatus(false);
            baseJson.setMessage(e.getMessage());
        }
        return baseJson;
    }
}
